<?php
/*
+ ---------------------------------------------------------------------- +
| e107Shop - An e-commerce plugin for the e107 content management system |
|                                                                        |
| ByOrder Europe 2007-2008                                               |
| http://e107shop.com                                                    |
| patrick@byorder.nl                                                     |
|                                                                        |
| Released under the terms and conditions of the LGPL                    |
|                                                                        |
| $Revision: 1.0                                                         |
| $Date: 2008/08/20                                                      |
| $Author: Bieleke                                                       |
+ ---------------------------------------------------------------------- +
*/

/*
    Function : e107shop_process_order
    -----------------------------------------------------------
    Parameters : $theorder        The order number
                 $thestatus        The status of the order
                 $thecartnumber    The id of the cart
                 $thegateway     The payment method used
                 $theregion        The region the customer is in
                 $coupon        A coupon if used
    ===========================================================
    Takes the contents of the shopping cart and inserts it into
    the orders table, so it is seen as an order, rather than a 
    pending shopping cart, allows the user to, make new orders
    ===========================================================
*/

require_once(e_LANGUAGEDIR.e_LANGUAGE."/lan_signup.php");
require_once(e_HANDLER."mail.php");

function e107shop_process_order($theorder, $thestatus, $thecartnumber, $thegateway, $theregion, $coupon){
    global $e107shop_db_name, $sql, $shop_settings, $tp;
    $sql2 = new db;
    $sql55 = new db;
    $theorder      = $tp->toDB($theorder);
    $thestatus     = $tp->toDB($thestatus);
    $thecartnumber = $tp->toDB($thecartnumber);
    $thegateway    = $tp->toDB($thegateway);
    $theregion     = $tp->toDB($theregion);
    $coupon        = $tp->toDB($coupon);
    if ($theregion == '') $theregion = e107shop_get_cust_info($theorder, "region");
    if($thestatus == "complete" || $thestatus == "pending") {
        if($sql55->db_Select($e107shop_db_name['cart'], "*", "cart_ID='".$thecartnumber."'")){
            //
            // Add each row into a new row in the orders table with status of "paid".
            //
            if(USER){
                $username = USERNAME;
            } else {
                $username = "Guest";
            }
            $i=1;
            $product_price = '';
            $postage_price = '';

            while($row=$sql55->db_Fetch()) {
                $line_product_price = e107shop_get_product_field($row["productID"], "special_price");
                if (floatval($line_product_price) == 0) 
                    $line_product_price = e107shop_get_product_field($row["productID"], "product_price");
                // Now check if there are option related tot he product
                $options = explode("|", $row["option"]);
                if(is_array($options)) {
                    foreach ($options as $value) {
                        $line_option_price = e107shop_get_option_field($value, "optval");
                        $line_product_price += $line_option_price;
                    }
                }
                $product_price += $line_product_price * $row['quantity'];
                $product_total_price = $line_product_price * $row['quantity'];
                // no need to calculate postage price here, cause it is not stored.
                if ($thestatus == "pending") {
                    $done = $sql2->db_Insert($e107shop_db_name['orders'], "0, '".$row["cart_ID"]."','". $row["productID"]."','"
                    . $row["quantity"]."','". $row["option"]."', '".$row["order_number"]."', 'pending', '"
                    .e107shop_get_dateformat()."', '".$thegateway."', '".$username."', '".$theregion."', '"
                    .$coupon."', '".$line_product_price."', '".$row["field1"]."', '".$row["field2"]."', '"
                    .$row["field3"]."', '".$row["field4"]."', '".$row["field5"]."', '".$row["field6"]
                    ."', '".$row["field7"]."', '".$row["field8"]."', '".$row["field9"]."', '".$row["field10"]
                    ."', '".$row["field11"]."', '".$row["field12"]."', '".$row["field13"]."', '".$row["field14"]
                    ."', '".$row["field15"]."', '".$row["field16"]."', '".$row["field17"]."', '".$row["field18"]
                    ."', '".$row["field19"]."', '".$row["field20"]."'");
                    if ($done > 0) {
                        if ($success!="2") {
                            $success = "1";
                        }                             
                    } else {
                        $success = "2";
                        e107shop_send_email(2, $theorder);
                    }
                } 
            }
            // TODO: Create a table for bookkeeping where you can store the invoices.
            //       Then you can add the information below to that table.

            /*$product_price = roundfix(e107shop_calculate_excl($product_price), 2);        
            $postage_price = roundfix($postage_price, 2);
            $subtotal = roundfix($product_price + $postage_price, 2);
            $tax = roundfix(e107shop_calculate_tax($subtotal), 2);
            $total = $subtotal + $tax;*/
            if (($success=="1") || ($success=="2")) {
                    e107shop_send_email($success, $theorder);
            } 
        } else {
            $success = "3";
            e107shop_send_email(3, $theorder);
        }        
    } else if($thestatus=="failed") {
        $success = "4";
        e107shop_send_email(4, $theorder);
    }
    $sql->db_Delete($e107shop_db_name['cart'], "cart_ID='".$thecartnumber."'");
    // only display this when the payment is offline, otherwise continue process_pay
    if ($thegateway == "offline") {
        header("location:order.php?s=".$success."&o=".$theorder);
    }
}

/*
    Function : e107shop_pay_order
    --------------------------------------------
    Parameters : $ordernr        The order number
    ============================================
    Give the order the status paid
    ============================================
*/

function e107shop_pay_order($ordernr) {
    global $e107shop_db_name, $sql, $shop_settings, $tp;
    $sql2 = new db;
    $ordernr = $tp->toDB($ordernr);
    $done = $sql2->db_Update($e107shop_db_name['orders'], "status='paid', last_mod='".e107shop_get_dateformat()."' where order_number='".$ordernr."'");
    if ($done > 0) {
        if(e107shop_check_for_downloads($ordernr)>0) {
            $success = "1";
            e107shop_send_email(5, $ordernr);
        } else {
            $success = "1";
            e107shop_send_email(6, $ordernr);
        }
        //
        // subtract 1 from the stock on hand
        //
        $sql3 = new db;
        $sql4 = new db;
        $sql5 = new db;
        $sql3->db_Select($e107shop_db_name['orders'], "*", "order_number='".$ordernr."'");
        while($row2=$sql3->db_Fetch()) {
            $productID = $row2['productID'];
            $quantity = $row2['quantity'];
            $sql4->db_Select($e107shop_db_name['products'], "*", "ID=".$productID);
            while($row3=$sql4->db_Fetch()) {
                $stock = $row3["stock_on_hand"];
                $stock = $stock - $quantity;
                $sql5->db_Update($e107shop_db_name['products'], "stock_on_hand=".$stock." where ID=".$productID);
            }
        }
    }
}


/*
    Function : e107shop_display_order
    ---------------------------------------------------------------
    Parameters : $theorder        The orderid
                 $thestatus        The status of the order
    ===============================================================
    Once the order is inserted into the database we need to display
    a receipt and other information for the customer. 
    ===============================================================    
*/

function e107shop_display_order($theorder, $thestatus) {
    global $e107shop_db_name, $shop_settings, $tp, $debugOrder;
    $theorder  = $tp->toDB($theorder);
    $thestatus = $tp->toDB($thestatus);
    $theregion = e107shop_get_cust_info($theorder, "region");
    $display = "<br /><center><span style='text-align: center; font-size: 14pt;'>"
    .lan_order_thanks."</span></center>
    <br /><table class='fborder' width='100%'>
    <tr><td class='forumheader' colspan='4'>&nbsp;</td></tr>
    <tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>
    <tr>
    <td>&nbsp;<b>".lan_order_number."</b></td>
    <td colspan='3'><b>".$theorder."</b></td>
    </tr>
    <tr>
    <td>&nbsp;<b>".lan_order_status."</b></td>
    <td colspan='3'><b>".e107shop_get_order_status($theorder)."</b></td>
    </tr>
    <tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>
        <tr>
                <td class='forumheader' style='text-align: left;'>
                    <strong>".lan_global_product_name."</strong>
                </td>
                <td class='forumheader'>
                    <strong>".lan_global_quantity."</strong>
                </td>
                <td class='forumheader'>
                    <strong>".lan_global_price_per_item."</strong>
                </td>
                <td class='forumheader'>
                    <strong>".lan_global_total."</strong>
                </td>
            </tr>
        <tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>";

    $sql=new db();
    $sql2=new db();
    $tblProducts=new db();
    $customFields = array();
    $dbrows = 0;    
    if($sql->db_Select($e107shop_db_name['orders'], "*", "order_number='".$theorder."' order by lineID")) {
        $gateway = "";
        while($row = $sql -> db_Fetch()){
            $customFields = array($row['field1'], $row['field2'], $row['field3'], $row['field4'], $row['field5'], 
            $row['field6'], $row['field7'], $row['field8'], $row['field9'], $row['field10'], 
            $row['field11'], $row['field12'], $row['field13'], $row['field14'], $row['field15'], 
            $row['field16'], $row['field17'], $row['field18'], $row['field19'], $row['field20']);
            $coupon = $row["coupon"];
            $line_product_price = $row["sale_price"];
            $product_total_price = $line_product_price * $row['quantity'];
            $product_price += $line_product_price * $row['quantity'];
            $gateway = $row['gateway'];
            // Calculate the postage price
            if($shop_settings["postage_method"] == "3"){
                $quantity += $row['quantity'];
                // always reset the postage price, cause we only want one calculation
                // with the exact amount of quantity
                $postage_price = e107shop_get_postage_price($row["productID"], $quantity, $theregion);
            } else {
                $postage_price += e107shop_get_postage_price($row["productID"], $row['quantity']);
            }
            //
            // Display each item from the cart
            //
            
            if ($dbrows > 0) {
                $display .="<tr><td colspan='4'><hr /></td></tr>";
            }
            
            $display .="<tr>
                    <td><div>&nbsp;"
                    .e107shop_get_product_field($row["productID"], "product_name")."</div>";
            // check if there are product-options before filling the table
            $options = explode("|", $row["option"]);
            if (is_array($options)) {
                if ($options['0']) $display .= "<div style='height: 10px;'>
                                            </div><div>&nbsp;<b>".lan_global_options."</b>";
                foreach ($options as $value) {
                    if ($sql2->db_Select($e107shop_db_name['product_options'], "*", "ID='".$value."'")) {
                        while ($row2=$sql2->db_Fetch()) {
                            $display .= "<br />&nbsp;".$row2["option_group"].": ".$row2['optname'];
                        }
                    }
                }
                if ($options['0']) $display .= "</div>";
            }
            // now check if the product is customized by the customer
            $firstRecord = 0;
            if ($customFields[0] != '') {
                // retrieve the names of the custom product fields
                $tblProducts->db_Select($e107shop_db_name['products'], "*", "ID='".$row['productID']."'");
                $tblProductsRow = $tblProducts->db_Fetch();
                $customProductFields = array($tblProductsRow['fname_1'], $tblProductsRow['fname_2'], $tblProductsRow['fname_3'], $tblProductsRow['fname_4'], $tblProductsRow['fname_5'], 
                $tblProductsRow['fname_6'], $tblProductsRow['fname_7'], $tblProductsRow['fname_8'], $tblProductsRow['fname_9'], $tblProductsRow['fname_10'], 
                $tblProductsRow['fname_11'], $tblProductsRow['fname_12'], $tblProductsRow['fname_13'], $tblProductsRow['fname_14'], $tblProductsRow['fname_15'], 
                $tblProductsRow['fname_16'], $tblProductsRow['fname_17'], $tblProductsRow['fname_18'], $tblProductsRow['fname_19'], $tblProductsRow['fname_20']);
                $display .= "<div style='height: 10px;'>
                </div>
                <div>&nbsp;<b>".lan_custom_fields."</b>";
                foreach ($customFields as $value) {
                    if ($value != '') $display .= "<br />&nbsp;".$customProductFields[$firstRecord].": ".$value;
                    $firstRecord += 1; 
                }
                $display .= "</div>";
            }
            // check if tax is inclusive, if it is we need to recalculate
            if ($shop_settings['tax_inc'] == 1) {
                $line_product_price = roundfix(e107shop_calculate_excl($line_product_price, $shop_settings['tax_rate']), 2);
                $product_total_price = roundfix(e107shop_calculate_excl($product_total_price, $shop_settings['tax_rate']), 2);
            } else {
                $line_product_price = roundfix($line_product_price, 2);
                $product_total_price = roundfix($product_total_price, 2);
            }
            $display .= "</td>
                    <td>                        
                        <center>".$row["quantity"]."</center>
                    </td>
                    <td>
                    <center>".$shop_settings["currency_symbol"].e107shop_get_numformat($line_product_price)."</center>
                    </td>
                    <td style='text-align: right;'>".$shop_settings["currency_symbol"]
                    .e107shop_get_numformat($product_total_price)."&nbsp;</td></tr>";
                    
            $dbrows++;
        }
        $display .= "<tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>
                    <tr><td class='forumheader' colspan='4'>&nbsp;</td></tr>
                    <tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>";
        
        // calculate and add the tax
        if ($shop_settings['tax_inc'] == 1) $product_price = roundfix(e107shop_calculate_excl($product_price, $shop_settings['tax_rate']), 2);
        
        // Set and Check the coupon amount
        $coupon_amount = 0;
        if($coupon) {
            $coupon_amount = e107shop_apply_coupon($product_price, $coupon);
            $midtotal = $product_price - $coupon_amount;
        }
        
        $postage_price = roundfix($postage_price, 2);
        $subtotal = roundfix((($product_price - $coupon_amount) + $postage_price), 2);
        $tax = roundfix(e107shop_calculate_tax($subtotal, $shop_settings['tax_rate']), 2);
        $total = $subtotal + $tax;
        
        $display .= "<tr><td colspan='3' style='text-align: right'>".lan_price_exclusive."&nbsp;</td>
        <td style='text-align: right'>".$shop_settings["currency_symbol"].e107shop_get_numformat($product_price)
        ."&nbsp;</td></tr>";
        
        if ($coupon_amount > 0) {
            $display .= "<tr><td colspan='3' style='text-align: right'>".lan_global_discount."&nbsp;</td>
            <td style='text-align: right'>".$shop_settings["currency_symbol"]."-".e107shop_get_numformat($coupon_amount)
            ."&nbsp;</td></tr>";
            $display .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>".lan_global_subtotal."&nbsp;</td>
            <td style='text-align: right; font-weight: bold;'>".$shop_settings["currency_symbol"].e107shop_get_numformat($midtotal)
            ."&nbsp;</td></tr>";
        }

        $display .= "<tr><td colspan='3' style='text-align: right'>".lan_global_postage."&nbsp;</td>
        <td style='text-align: right'>".$shop_settings["currency_symbol"].e107shop_get_numformat($postage_price)
        ."&nbsp;</td></tr>";
        
        $display .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>"
        .lan_global_subtotal."&nbsp;</td><td style='text-align: right; font-weight: bold;''>"
        .$shop_settings["currency_symbol"].e107shop_get_numformat($subtotal)."&nbsp;</td></tr>";

        $display .= "<tr><td colspan='3' style='text-align: right'>".lan_global_tax."&nbsp;</td>
        <td style='text-align: right'>".$shop_settings["currency_symbol"].e107shop_get_numformat($tax)
        ."&nbsp;</td></tr>";

        $display .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>"
        .lan_global_total_price."&nbsp;</td><td style='text-align: right; font-weight: bold;''>"
        .$shop_settings["currency_symbol"].e107shop_get_numformat($total)."&nbsp;</td></tr>";
        
        $extraPaymentInfo = "";
        $extraCost = e107shop_calculate_extra_payment($gateway, $total, $extraPaymentInfo);
        $extraCost = roundfix($extraCost, 2);
        $grandTotal = roundfix($total + $extraCost, 2);
        // gateway extra cost
        if(trim($extraPaymentInfo) != "") {
            $display .= "<tr><td colspan='3' style='text-align: right'>".constant("lan_gateway_".$gateway)."&nbsp;</td>
            <td style='text-align: right'>".$shop_settings["currency_symbol"].e107shop_get_numformat($extraCost)
            ."&nbsp;</td></tr>";
    
            $display .= "<tr><td colspan='3' style='text-align: right; font-weight: bold;'>"
            .lan_global_total_price."&nbsp;</td><td style='text-align: right; font-weight: bold;''>"
            .$shop_settings["currency_symbol"].e107shop_get_numformat($grandTotal)."&nbsp;</td></tr>";
        } 
        $display .= "<tr><td colspan='4'><div style='height: 5px;'>&nbsp;</div></td></tr>";
    }
    $display .="</table>";
    $tblProducts->db_Close();
    return $display;
}

/*
    Function : e107shop_get_customer_info
    ------------------------------------------------------
    Parameters : $theorder    The orderid
                 $option    The data you want to read
    ======================================================
    Grabs the customers stored information for the invoice
    ======================================================    
*/

function e107shop_get_cust_info($theorder, $option) {
    global $e107shop_db_name, $sql, $tp;
    $theorder = $tp->toDB($theorder);
    $option   = $tp->toDB($option);
    // looks up user who actually made the order
    $sql->db_Select($e107shop_db_name['orders'], "*", "order_number='".$theorder."'"); 
    while($row = $sql -> db_Fetch())
    // assigns variable $customer_uname to the person who made the order    
    $customer_uname = $row["theuser"];
   
    $sql->db_Select($e107shop_db_name['customer_information'], "*", "username='".$customer_uname."'");
    while($row = $sql -> db_Fetch()){
        //
        // Fetch the details and store them in variables so the HTML only needs to be written once
        //
        $customer_details = $row["customer_name"] . " " . $row["customer_last_name"]."<br />";
        $customer_details .= $row["customer_address1"] . " <br />";
        if($row["customer_address2"] != ""){
            $customer_details .= $row["customer_address2"] . "<br />";
        }
        $customer_details .= $row["customer_city"] . ", " . $row["customer_state"] . "<br />";
        $customer_details .= $row["customer_country"] . ", " . $row["customer_zip"];
            
        $customer_details.="<br />".$row["customer_email"]."<br />";
           
        switch($option) {
            case "email":
                return $row["customer_email"];
                break;
            case "region":
                return $row["customer_region"];
                break;
            default:
                return $customer_details;
                break;
        }
    }
}

/*
    Function : e107shop_delete_cart
    -------------------------------
    Parameters : $theorder = The order id
    =====================================
    Deletes the content of the users cart
    =====================================    
*/

function e107shop_delete_cart($theorder) {
    global $e107shop_db_name, $sql, $tp;
    $theorder = $tp->toDB($theorder);
    $sql->db_Delete($e107shop_db_name['cart'], "order_number='".$theorder."'");
}

/*
    Function : e107shop_get_order_date
    ------------------------------------------
    Parameters : $theorder = The orderid
    ==========================================
    Grabs the date the order was last modified
    ==========================================
*/

function e107shop_get_order_date($theorder){
    global $e107shop_db_name, $sql, $tp;
    $theorder = $tp->toDB($theorder);
    $sql->db_Select($e107shop_db_name['orders'], "`last_mod`", "order_number='".$theorder."'");
    while($row=$sql->db_Fetch()){
        $theDate=$row["last_mod"];
    }
    
    return $theDate;
}

/*
    Function : e107shop_get_order_date
    ------------------------------------------
    Parameters : $theorder
    ==========================================
    Grabs the date the order was last modified
    ==========================================    
*/

function e107shop_get_payment_method($theorder){
    global $e107shop_db_name, $sql, $tp;
    $theorder = $tp->toDB($theorder);
    $sql->db_Select($e107shop_db_name['orders'], "`gateway`", "order_number='".$theorder."'");
    while($row=$sql->db_Fetch()){
        $theGateway=$row["gateway"];
    }
    // TODO: this gateway list should be extended, or there should be
    //       a function to read it out from a database or something ?
    if ($theGateway == "offline") {
        $theGateway = lan_gateway_offline;
    }
    return $theGateway;
}

/*
    Function : e107shop_get_product_options_for_invoice
    ---------------------------------------------------
    Parameters : $optionid = the ide of the option
                 $field    = the field you want to read
    ===================================================
    This function is used to grab product options 
    and their details for the invoice.
    ===================================================
*/

function e107shop_get_product_options_for_invoice($option_ID, $field) {
    global $e107shop_db_name;
    foreach(explode("|", $option_ID) as $options) {
        $options = (int)$options;
        $sql=new db;
        $sql->db_Select($e107shop_db_name['product_options'], "*", "ID='".$options."'");
        while($row = $sql -> db_Fetch()){
            if($field == "optname") {
                $field2.=$row[$field]."\n";
            } else {
                if($row["opter"]=="+") {
                    $field2+=$row[$field];
                } else if($row["opter"]=="-") {
                    $field2-=$row[$field];
                }
            }
        }
    }    
    return $field2;
}

/*
    Function : e107shop_send_email
    ------------------------------
    Parameters : $status = The status of the order
                 $order  = The orderid
    ==============================================
    Grabs the customers region
    ==============================================
*/

function e107shop_send_email($status, $order) {
    global $shop_settings, $tp;
    $status = $tp->toDB($status);
    $order  = $tp->toDB($order);
    switch($status){
        // Successful order
        Case "1":
            // Email the siteadmin to make them aware of the purchase
            sendemail(SITEADMINEMAIL, e107shop_admin_purchase_message("", "t1"), 
            e107shop_admin_purchase_message($order, "s1"));
            // Send the details of the order to the shop owner
            sendemail($shop_settings["order_email"], e107shop_admin_purchase_message("", "t1"), 
            e107shop_admin_purchase_message($order, "s2"));
            // Email the customer with the order details
            sendemail(e107shop_get_cust_info($order, "email"), e107shop_admin_purchase_message("", "t2"), 
            e107shop_customer_purchase_message($order, "s"));
            break;
        // process error
        Case "2":
            // Email the siteadmin to make them aware of failed order
            sendemail(SITEADMINEMAIL, e107shop_admin_purchase_message("", "t3"), 
            e107shop_admin_purchase_message($order, "p1"));
            // Send the details of the failed order to the show owner
            sendemail($shop_settings["order_email"], e107shop_admin_purchase_message("", "t3"), 
            e107shop_admin_purchase_message($order, "p2"));
            // Email the customer with the details of the failed order
            sendemail(e107shop_get_cust_info($order, "email"), e107shop_admin_purchase_message("", "t4"), 
            e107shop_customer_purchase_message($order, "p"));
            break;
        // Cart not found
        Case "3":
            // Email the siteadmin to make them aware of the purchase
            sendemail(SITEADMINEMAIL, e107shop_admin_purchase_message("", "t5"), 
            e107shop_admin_purchase_message($order, "c1"));
            // Send the details of the order to the store emails
            sendemail($shop_settings["order_email"], e107shop_admin_purchase_message("", "t5"),
            e107shop_admin_purchase_message($order, "c2"));
            // Email the customer with the order details
            sendemail(e107shop_get_cust_info($order, "email"), e107shop_admin_purchase_message("", "t6"), 
            e107shop_customer_purchase_message($order, "c"));
            break;
        // Payment Error
        Case "4":
            // Email the siteadmin to make them aware of the failing payment
            sendemail(SITEADMINEMAIL, e107shop_admin_purchase_message("", "t7"), 
            e107shop_admin_purchase_message($order, "pe1"));
            // Send the details of the failing payment to the store emails
            sendemail($shop_settings["order_email"], e107shop_admin_purchase_message("", "t7"), 
            e107shop_admin_purchase_message($order, "pe2"));
            // Email the customer with the failed payment details
            sendemail(e107shop_get_cust_info($order, "email"), e107shop_admin_purchase_message("", "t8"), 
            e107shop_customer_purchase_message($order, "pe"));
            break;
        // Non-Tangible Product
        Case "5":
            // Email the siteadmin to make them aware the payment for the downloads is done
            sendemail(SITEADMINEMAIL, e107shop_admin_purchase_message("", "pnt1") , 
            e107shop_admin_purchase_message($order, "nt1"));
            // Send the details of the payment for the downloads to the store emails
            sendemail($shop_settings["order_email"], e107shop_admin_purchase_message("", "pnt1"), 
            e107shop_admin_purchase_message($order, "nt2"));
            // Email the customer with the links to the downloads
            sendemail(e107shop_get_cust_info($order, "email"), e107shop_admin_purchase_message("", "pnt2"), 
            e107shop_customer_purchase_message($order, "nt"));
            break;
        // Payment of the order (normal products, no digital downloads)
        Case "6":
            // Email the siteadmin to make them aware the payment is done
            sendemail(SITEADMINEMAIL, e107shop_admin_purchase_message("", "paid") , 
            e107shop_admin_purchase_message($order, "pay1"));
            // Send the details of the payment to the store email
            sendemail($shop_settings["order_email"], e107shop_admin_purchase_message("", "paid"), 
            e107shop_admin_purchase_message($order, "pay2"));
            // Email the customer with an order paid message
            sendemail(e107shop_get_cust_info($order, "email"), e107shop_admin_purchase_message("", "paid2"), 
            e107shop_customer_purchase_message($order, "pay"));
            break;
    }
}



function e107shop_get_sale_price($product, $options, $quantity) {
    if(e107shop_get_product_field($product, "special_price")=="")
    {
        $product_price = e107shop_get_product_field($product, "product_price");
    }
    else
    {
        $product_price = e107shop_get_product_field($product, "special_price");
    }

    //
    // Get the option additional price
    //
    $option_price = e107shop_get_product_options_for_cart($options, "optval");

    $price = $product_price + $option_price;
    $price = $price * $quantity;
    return $price;
}

function e107shop_get_order_status($order) {
    global $e107shop_db_name, $tp;
    $order = $tp->toDB($order);
    $ordb = new db();
    $ordb->db_Select($e107shop_db_name['orders'], "status", "order_number='".$order."'");
    while ($row = $ordb->db_Fetch()) {
        $result = $row['status'];
    }
    switch ($result) {
        case "pending":
            return "<span style='color: red'>".constant("lan_order_pending")."</span>";
            break;
        case "paid":
            return "<span style='color: orange'>".constant("lan_order_paid")."</span>";
            break;
        case "complete":
            return "<span style='color: green'>".constant("lan_order_complete")."</span>";
            break;
    }
}

function e107shop_get_order_field($order, $product, $field) {
    global $e107shop_db_name, $tp;
    $ordb = new db();
    $order   = $tp->toDB($order);
    $product = (int)$product;
    if ($product != 0) {
        $ordb->db_Select($e107shop_db_name['orders'], "*", "order_number='".$order."' AND productID='".$product."'");
    } else {
        $ordb->db_Select($e107shop_db_name['orders'], "*", "order_number='".$order."'");
    }
    while ($row = $ordb->db_Fetch()) {
        $result = $row[$field];
    }
    return $result;
}

//
// Un-used function but kept for later integrations if needed, simply 
// makes an order id string rather than number
//
//
//function e107shop_create_order_id($order){
//    //
//    // Turn the order string into an array for transforming
//    // the string will be checked and grown so it is 
//    // an unlimited ID
//    //
//    $id_length = strlen($order);    
//    $i = 0;
//    $new_id = array();
//    while($i < $id_length)
//    {
//        $character = $order{$i};        
//        if(ord($character) == 90 || $character==9){
//            $do_next = $i;
//            $do_next += 1;
//            
//            if(ord($character) == 90){
//                $next = "num";
//            }
//            else
//            {
//                $next = "chr";                
//            }
//        }
//            
//        array_push($new_id, $character);
//    $i++;
//    }
//
//    if($do_next==$id_length){
//        if($next=="num"){    
//            echo 1;
//            array_push($new_id, chr(48));
//        }
//        else
//        {
//            echo 2;
//            array_push($new_id, chr(64));
//        }
//    }
//
//    $add_char = ord($new_id[$do_next]) + 1;
//    $new_id[$do_next] = chr($add_char);
//        
//    echo "<pre>";
//    print_r($new_id);
//    echo "</pre>";
//}
//e107shop_create_order_id("Z9");
